package com.tedu.v2_3;

import jdk.management.resource.internal.inst.DatagramSocketRMHooks;

import java.io.*;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
/**
 * 练习：1.Client 添加 IP 功能
 *     2.Server 关闭通讯，代码整洁，写Client
 *  Version3.0 升级  双向链接【客户端与服务器相互说话】
 */
public class Client {
    private Socket socket;
    public Client(){
        try {
            socket = new Socket("172.20.62.212", 1234);
        }catch(NullPointerException e){
            System.out.println("友情提示:");
        }catch(UnknownHostException e){
            System.out.println("友情提示：IP传入错误");
        }catch(ConnectException e){
            System.out.println("客户端链接失败");
        }
        catch (IOException e) {
            System.out.println("客户端链接服务器端失败了，提示：检查IP/端口");
        }
        }
    public void start()  {
        PrintWriter pw=null;
        try {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
            pw = new PrintWriter(bw, true);
            System.out.println("对服务器端说话：");
            Scanner input=new Scanner(System.in);
            String line=null;
            while(true){
                line=input.nextLine();
                pw.println(line);
                System.out.println("写出成功了~");
            }
        }catch(UnsupportedEncodingException e){
            System.out.println("客户端/服务器端编码集有问题");
        } catch (IOException e) {
            System.out.println("客户端链接服务器端：IO流操作出现错误！");
        } finally {
            if(pw!=null)
                pw.close();

        }
        }

    public static void main(String[] args) throws IOException {
        new Client().start();
    }
    }
